<?php
namespace app\auth\model;
use \think\{Loader};
class AppletBase{
    protected $gzhAppid ;        //AppID
    protected $gzhSecret;    //秘钥
    public static $wxConfInstance;
    public $error; //错误信息
    public function __construct($options){
        if(!empty($options['web_id'])){
            $this->wxConfInstance($options['web_id']);
        }else{
            if(!empty($options['appid']) && !empty($options['appsecret'])){
                $this->gzhAppid = $options['appid'];
                $this->gzhSecret = $options['appsecret'];
            }else{
                return false;
            }
        }
    }

    public function wxConfInstance(int $web_id=0){
        if (is_null(self::$wxConfInstance)) {
            if($web_id){
                self::$wxConfInstance = Loader::model('wechat/MiniProgram');
                $wx_config_info = self::$wxConfInstance->get_table_info(['web_id' => $web_id],'*','WechatConfig');
                if(!empty($wx_config_info['appid']) && !empty($wx_config_info['appsecret'])){
                    $this->gzhAppid = $wx_config_info['appid'];
                    $this->gzhSecret = $wx_config_info['appsecret'];
                }
            }
        }
        return self::$wxConfInstance;
    }

    /**
     * 获取小程序授权token
     */
    public function get_token(){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->gzhAppid.'&secret='.$this->gzhSecret;
        $result = $this->https_request($url);
        return !empty($result['access_token'])?$result['access_token']:null;
    }

    public function create_qr_code($params,$module='common',$is_forever=true){
        //存储路径
        $path = [
            'local' => ROOT_PATH.'public'.DS,
            'main' => 'uploadfile'.DS.config('web_id').DS.$module,
        ];
        $filename = time().".png";
        $file_local_path = $path['local'].$path['main'].$filename;
        $access_token = $this->get_token();
        if($is_forever){
            $request_data = [
                "path"  => "src/pages/home/home?".$params,
                "width" => "400"
            ];
            $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=';
        }else{
            $request_data = [
                "scene" => urlencode($params),
                "path"  => "src/pages/home/home",
                "width" => "400"
            ];
            $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=';
        }
        $url .= $access_token;
        $result = $this->https_request($url,json_encode($request_data),false);
        $res_arr = json_decode($result,true);
        if(is_null($res_arr)){
            if(!file_exists($path['local'].$path['main']))  mkdir($path['local'].$path['main'], 0755, true);
            file_put_contents($file_local_path,$result);
            if(file_exists($file_local_path)){
                return $file_local_path;
            }else{
                $res_arr = ['errcode'=>0,'errmsg'=>'下载小程序码失败'];
            }
        }
        return $res_arr;
    }

    /**
     * 批量小程序码生成
     * @param  Array   $params     [description]
     * @param  string  $module     [description]
     * @param  boolean $is_forever [description]
     * @return [type]              [description]
     */
    public function create_qrcode_batch(Array $params,$module='preview',$is_forever=true){
        $web_id = !empty(config('web_id'))?config('web_id'):0;
        $qrcode_list = [];
        $access_token = $this->get_token();
        if(is_null($access_token)){
            //获取access_token失败
            $this->error = "get access_token error!";
            return false;
        }
        $upload_handler = \think\Loader::controller('auth/Base');
        $qiniu_domain = config('qiniu_https')['HTTPS_DOMAIN'];
        foreach ($params as $key => $value) {
            if(is_array($value)){
                $value = http_build_query($value);
            }
            if($is_forever){
                $request_data = [
                    "path"  => "pages/auth/auth?".$value,
                    "width" => "400"
                ];
                $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=';
            }else{
                $request_data = [
                    "scene" => urlencode($value),
                    "path"  => "pages/auth/auth",
                    "width" => "400"
                ];
                $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=';
            }
            $url .= $access_token;
            $result = $this->https_request($url,json_encode($request_data),false);
            $res_arr = json_decode($result,true);
            if(is_null($res_arr)){
                $result_img = $upload_handler->qiniu_put($result,"live/{$web_id}/{$module}/");
                if(!empty($result_img) && $result_img['status']==1){
                    $qrcode_list[$key] = $qiniu_domain.$result_img['org_data'];
                }else{
                    $qrcode_list[$key] = $result_img;
                }
            }else{
                $qrcode_list[$key] = $res_arr;
            }
        }
        return $qrcode_list;
    }


    /**
     * https请求（支持GET和POST）
     * @param  string  $url            请求地址
     * @param  json    $data           请求数据
     * @param  boolean $is_json_decode 是否把响应内容解析成json格式
     * @return [type]                  [description]
     */
    public function https_request($url, $data = null,$is_json_decode=true) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $is_json_decode?json_decode($output,true):$output;
    }


    public function getWxOpenId($code){
        $data = [
            'appid' => $this->gzhAppid ,
            'secret' =>$this->gzhSecret,
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        ];
        $getUrl = 'https://api.weixin.qq.com/sns/jscode2session?' . http_build_query($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $getUrl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        return json_decode($data);
    }

}